package Util;

use Digest::CRC qw(crc16);

# Runs a command in a shell with a given timeout
# $_[0] -- command
# $_[1] -- timeout
# returns ($returncode, @output)
# TODO: also return STDERR
sub run_command
{
        (my $command, my $timeout) = @_;

        my $pid = open(PIPE, "$command |") or die $!;
        my @output;
        eval {
                local $SIG{ALRM} = sub {die "TIMEDOUT"};
                alarm(int($timeout));
                @output = <PIPE>;
                close(PIPE);
                alarm(0);
        };
        if ($@) {
                die $@ unless $@ =~ /TIMEDOUT/;
                kill 9, $pid;
                close(PIPE);    ## needed??
                $? ||= 9;
        }
        return ($?, @output);
}

# Returns given text in bold
sub bold
{
        return chr(2) . $_[0] . chr(2);
}

sub color_nick
{
	my $colorid = 2 + (int(crc16($_[0])) % 9);

	if (length($colorid) < 2) {    # Irc colors should be 2 bytes, so for example instead of 1, it should be 01
		$colorid = "0" . int($colorid);
	}
	return chr(3) . $colorid . $_[0] . chr(15);
}

# Insert element after a certain index in an array
# $_[0] -- array
# $_[1] -- index
# $_[2] -- data
# returns new array
sub insert_after(\@$$)
{
        my $array_ref = shift;
	my @end = splice(@{$array_ref}, $_[0] + 1, (@{$array_ref} - $_[0]), $_[1]);
	return push(@{$array_ref}, @end);
}

# Returns a human readable string representing elapsed time
# from given timestamp.
# $_[0] - unix timestamp
# returns a human readable string
# TODO: possibly allow for remaining time counting
sub howlongago
{
        use integer;
        my $outstr;
        my $diff = time() - $_[0];
        my $days = $diff / (3600 * 24);
        if ($days > 7) {
                return $days . "d temu";
        }
        elsif ($days > 0) {
                $outstr = $days . "d ";
        }
        $diff -= $days * (3600 * 24);

        my $hours = $diff / 3600;
        if ($hours > 12) {
                return $outstr . $hours . "g temu";
        }
        elsif ($hours > 0) {
                $outstr = $outstr . $hours . "g ";
        }
        $diff -= $hours * 3600;

        my $minutes = $diff / 60;
        if ($minutes > 5) {
                return $outstr . $minutes . "m temu";
        }
        elsif ($minutes > 0) {
                $outstr = $outstr . $minutes . "m ";
        }
        $diff -= $minutes * 60;
        return $outstr . $diff . "s temu";
}
1;